<?php

namespace App\Repositories;

use App\Models\Bills;
use App\Models\EntryTally;
use App\Models\Network;
use App\Models\NetworkExpress;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class NetworkBillRepository extends BaseRepository
{
    /**
     *  REDIS_EXPIRES_FOR_WEEKS 缓存有效期一周
     */
    const REDIS_EXPIRES_FOR_WEEKS = 604800;

    public function model()
    {
        return EntryTally::class;
    }

    /**
     * 获取网点账单
     * Date: 2018/06/20
     * @author Tenny
     * @param $network_id
     * @param $limit
     * @param $name
     * @param $created_at
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getNetworkBills_v1($network_id, $limit, $name = false, $created_at = false)
    {
        $query = Network::query();
        if ($network_id !== false) {
            $query->where('network.id', '=', $network_id);
        }
        if ($name !== false) {
            $query->where('network.designation', '=', $name);
        }
        $network = $query
            ->with(["services" => function ($query) use ($created_at) {
                $query->with(['bills' => function ($query) use ($created_at) {
                    if ($created_at !== false) {
                        $date = [
                            date("Y-m-d 00:00:00", strtotime($created_at)),
                            date("Y-m-d 23:59:59", strtotime($created_at))
                        ];
                        $query->whereBetween('created_at', $date);
                    } else {
                        $query->whereBetween('created_at',
                            [
                                date("Y-m-d 00:00:00", time()),
                                date("Y-m-d 23:59:59", time()),
                            ]);
                    }
                    //$query->where('network.id', '=', 'sign_out_tally.network_id');
                }]);
            }])
            ->paginate($limit)
            ->toArray();
        //过滤数据(除去关联的非法数据
        if (is_array($network['data']) && count($network['data']) > 0) {
            foreach ($network['data'] as $key => $networks) {
                $id = $networks['id'];
                if (is_array($networks['services']) && count($networks['services']) > 0) {
                    foreach ($networks['services'] as $k => $services) {
                        if (is_array($services['bills']) && count($services['bills']) > 0) {
                            foreach ($services['bills'] as $ke => $bills) {
                                if (array_key_exists('network_id', $bills) && $bills['network_id'] != $id) {
                                    unset($network['data'][$key]['services'][$k]['bills'][$ke]);
                                }
                            }
                        }
                    }
                }
            }
        }
        //统计站点收件数，收入
        if (is_array($network['data']) && count($network['data']) > 0) {
            foreach ($network['data'] as $key => $networks) {
                $network_send_sum = 0;
                $network_return_sum = 0;
                $network_cost_sum = 0.00;
                if (is_array($networks['services']) && count($networks['services']) > 0) {
                    foreach ($networks['services'] as $k => $services) {
                        $send_sum = 0;
                        $return_sum = 0;
                        $cost_sum = 0.00;
                        if (is_array($services['bills']) && count($services['bills']) > 0) {
                            foreach ($services['bills'] as $ke => $bills) {
                                if (array_key_exists('status', $bills) && $bills['status'] == 0) {
                                    $send_sum += 1;
                                    $cost_sum = round($cost_sum + $bills['unit_price'], 2);
                                    $network_send_sum += 1;
                                    $network_cost_sum = round($cost_sum + $bills['unit_price'], 2);
                                } else {
                                    $return_sum += 1;
                                    $cost_sum = round($cost_sum * $bills['unit_price'], 2);
                                    $network_return_sum += 1;
                                    $network_cost_sum = round($cost_sum * $bills['unit_price'], 2);
                                }
                            }
                        }
                        $network['data'][$key]['services'][$k]['send_sum'] = $send_sum;
                        $network['data'][$key]['services'][$k]['return_sum'] = $return_sum;
                        $network['data'][$key]['services'][$k]['cost_sum'] = $cost_sum;
                    }
                }
                $network['data'][$key]['network_send_sum'] = $network_send_sum;
                $network['data'][$key]['network_return_sum'] = $network_return_sum;
                $network['data'][$key]['network_cost_sum'] = $network_cost_sum;
            }
        }
        return $network;
    }

    /**
     * 获取网点账单
     * Date: 2018/06/20
     * @author Tenny
     * @param $limit
     * @param $name
     * @param $created_at
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function getNetworkBills($limit, $name = false, $created_at = false)
    {
        $query = Bills::query();
        if ($name !== false) {
            $query->where('n.designation', 'like', '%' . $name . '%');
        }
        if ($created_at !== false) {
            $query->where('bills.date', '=', $created_at);
        }
        $bills = $query
            ->select(['bills.*', 's.designation as service_name', 'n.designation as network_name', DB::raw("sum(bills.total_sign) as network_total"), DB::raw("sum(bills.total_income) as network_total_income")])
            ->leftJoin('service as s', 'bills.service_id', '=', 's.id')
            ->leftJoin('network as n', 'bills.network_id', '=', 'n.id')
            ->groupBy('network_id')
            ->paginate($limit);
        return $bills;
    }

    /**
     * 获取网点账单
     * Date: 2018/06/20
     * @author Tenny
     * @param $network_id
     * @param $limit
     * @param $created_at
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getStationBills($network_id, $limit, $created_at = false)
    {
        $query = Bills::query();
        if ($network_id !== false) {
            $query->where('bills.network_id', '=', $network_id);
        }
        if ($created_at !== false) {
            $query->where('bills.date', '=', $created_at);
        } else {
            $query->where('bills.date', '=', date("Y-m-d", time()));
        }
        $bills = $query
            ->select(['bills.*', 's.designation as service_name', 'e.unit_price'])
            ->leftJoin('service as s', 'bills.service_id', '=', 's.id')
            ->leftJoin('network_express as e', function ($query) {
                $query->on('bills.service_id', '=', 'e.service_id')
                    ->on('bills.network_id', '=', 'e.network_id');
            })
            ->groupBy('bills.service_id')
            ->paginate($limit);
        return $bills;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}